package com.zhentao.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 客服转人工服务
 */
@Service
@Slf4j
public class CustomerServiceTransferService {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private AiConversationService conversationService;
    
    @Autowired
    private AiMessageService messageService;
    
    /**
     * 处理转人工请求
     * @param userId 用户ID
     * @param conversationId 会话ID
     * @param userMessage 用户消息
     * @return 转人工响应信息
     */
    public Map<String, Object> handleTransferToHuman(Integer userId, String conversationId, String userMessage) {
        log.info("处理转人工请求，用户ID: {}, 会话ID: {}, 消息: {}", userId, conversationId, userMessage);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 获取可用的客服
            User customerService = getAvailableCustomerService();
            
            if (customerService == null) {
                // 没有可用客服时的处理
                result.put("success", false);
                result.put("message", "抱歉，当前没有客服在线，请稍后再试或留言给我们。");
                result.put("type", "no_service_available");
                return result;
            }
            
            // 2. 创建转人工记录
            String transferInfo = createTransferRecord(userId, conversationId, customerService, userMessage);
            
            // 3. 保存转人工消息到数据库
            if (conversationId != null) {
                try {
                    messageService.saveAssistantMessage(
                        userId, 
                        conversationId, 
                        transferInfo, 
                        "transfer_system", 
                        null
                    );
                    
                    // 更新会话最后消息
                    conversationService.updateLastMessage(conversationId, "已转接人工客服");
                } catch (Exception e) {
                    log.error("保存转人工消息失败: {}", e.getMessage());
                }
            }
            
            // 4. 构建成功响应
            result.put("success", true);
            result.put("message", transferInfo);
            result.put("type", "transfer_success");
            result.put("customerService", Map.of(
                "id", customerService.getId(),
                "nickname", customerService.getNickname(),
                "phone", customerService.getPhone(),
                "avatar", customerService.getAvatar()
            ));
            
            log.info("转人工成功，客服: {}", customerService.getNickname());
            
        } catch (Exception e) {
            log.error("转人工处理失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "转人工服务暂时不可用，请稍后再试。");
            result.put("type", "system_error");
        }
        
        return result;
    }
    
    /**
     * 获取可用的客服
     * @return 客服用户信息
     */
    private User getAvailableCustomerService() {
        try {
            // 查询所有状态正常的客服用户
            // 根据您提供的数据，客服的用户名是"客服"，昵称是"人工客服"
            List<User> customerServices = userService.list(new QueryWrapper<User>()
                .eq("status", 1) // 正常状态
                .and(wrapper -> wrapper
                    .eq("username", "客服")
                    .or()
                    .like("nickname", "客服")
                    .or()
                    .like("nickname", "人工客服")
                )
            );
            
            if (customerServices.isEmpty()) {
                log.warn("没有找到可用的客服用户");
                return null;
            }
            
            // 如果有多个客服，随机选择一个（简单的负载均衡）
            if (customerServices.size() == 1) {
                return customerServices.get(0);
            } else {
                Random random = new Random();
                return customerServices.get(random.nextInt(customerServices.size()));
            }
            
        } catch (Exception e) {
            log.error("获取客服信息失败: {}", e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 创建转人工记录信息
     * @param userId 用户ID
     * @param conversationId 会话ID
     * @param customerService 客服信息
     * @param userMessage 用户消息
     * @return 转人工信息文本
     */
    private String createTransferRecord(Integer userId, String conversationId, User customerService, String userMessage) {
        StringBuilder transferInfo = new StringBuilder();
        
        transferInfo.append("您已成功转接人工客服，点击链接即可联系：\n\n");
        
        // 生成客服联系链接（这里使用一个示例链接，您可以根据实际需求修改）
        String contactLink = generateCustomerServiceLink(customerService, userId, conversationId);
        transferInfo.append("👉 [").append(contactLink).append("]\n");
        transferInfo.append("(").append(contactLink).append(")\n\n");
        
        transferInfo.append("人工客服将尽快为您服务，感谢您的耐心等待～ 😊");
        
        return transferInfo.toString();
    }
    
    /**
     * 生成客服联系链接
     * @param customerService 客服信息
     * @param userId 用户ID
     * @param conversationId 会话ID
     * @return 联系链接
     */
    private String generateCustomerServiceLink(User customerService, Integer userId, String conversationId) {
        // 这里可以根据您的实际业务需求生成不同类型的链接
        // 例如：跳转到客服聊天页面、拨打客服电话、发送邮件等
        
        // 方案1: 生成客服聊天链接
        if (customerService.getPhone() != null && !customerService.getPhone().isEmpty()) {
            // 如果有客服电话，生成电话联系方式
            return String.format("tel:%s", customerService.getPhone());
        }
        
        // 方案2: 生成邮件联系方式
        if (customerService.getEmail() != null && !customerService.getEmail().isEmpty()) {
            return String.format("mailto:%s?subject=用户咨询&body=用户ID:%s,会话ID:%s", 
                customerService.getEmail(), userId, conversationId);
        }
        
        // 方案3: 生成内部客服系统链接
        return String.format("https://customer-service.oceanbridge.com/chat?service_id=%s&user_id=%s&conversation_id=%s", 
            customerService.getId(), userId, conversationId);
    }
    
    /**
     * 检查是否为转人工请求
     * @param message 用户消息
     * @return 是否为转人工请求
     */
    public boolean isTransferRequest(String message) {
        if (message == null || message.trim().isEmpty()) {
            return false;
        }
        
        String lowerMessage = message.toLowerCase().trim();
        
        // 转人工关键词列表
        String[] transferKeywords = {
            "转人工", "人工客服", "人工服务", "联系客服", "客服", 
            "转接", "人工", "真人", "客服电话", "投诉", "建议",
            "不满意", "解决不了", "需要帮助", "manual", "human"
        };
        
        for (String keyword : transferKeywords) {
            if (lowerMessage.contains(keyword)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 获取客服统计信息
     * @return 客服统计数据
     */
    public Map<String, Object> getCustomerServiceStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 统计客服数量
            long totalCustomerServices = userService.count(new QueryWrapper<User>()
                .eq("status", 1)
                .and(wrapper -> wrapper
                    .eq("username", "客服")
                    .or()
                    .like("nickname", "客服")
                    .or()
                    .like("nickname", "人工客服")
                )
            );
            
            stats.put("totalCustomerServices", totalCustomerServices);
            stats.put("onlineCustomerServices", totalCustomerServices); // 简化处理，假设都在线
            stats.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            log.error("获取客服统计信息失败: {}", e.getMessage(), e);
            stats.put("error", e.getMessage());
        }
        
        return stats;
    }
}
